package com.schoolai.schoolset.config;

import ch.qos.logback.classic.pattern.MessageConverter;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.support.RetryTemplate;

/**
 * Copyright(C),2019-2025，XX公司
 * FileName:RabbitmqConfig
 * Author:bobby
 * 创建时间：2025/11/12 10:08
 * Description:rabbitmq配置类
 * History:
 * <auth>        <time>       <version>       <desc>
 * 作者          修改时间       版本号         描述
 */
@Configuration
public class RabbitmqConfig {
    @Autowired
    ConnectionFactory connectionFactory;
    /* 短信普通队列*/
    @Bean
    public Queue queue() {
        return new Queue("SMSQueue");
    }

    /* 实现ACK*/
    @Bean(name = "rabbitListenerContainerFactory")
    @Scope("prototype")
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        //开启手动 ack
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        RetryTemplate retryTemplate = new RetryTemplate();
        //指数退避策略 等待时间= 等待时间*倍数 ，即每一次的等待时间是上一次等待时间的n倍，
        //到达最大的等待时间之后就不在增加了，一直都是以最大的等待时间在等待。默认执行3次
        ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
        //初始等待时间
        exponentialBackOffPolicy.setInitialInterval(1000);
        //时间等待倍数
        exponentialBackOffPolicy.setMultiplier(2);
        //最大等待时间
        exponentialBackOffPolicy.setMaxInterval(5000);

        retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);

        factory.setRetryTemplate(retryTemplate);
        return factory;
    }
    @Bean(name="ackRabbitTemplate")
    @Scope("prototype")
    //必须是prototype类型
    public RabbitTemplate ackrabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        return template;
    }

}
